package com.hnust.controller.paper.autoPaperController;

import com.hnust.controller.MainController;
import com.hnust.domain.CourseData;
import com.hnust.domain.Result;
import com.hnust.fx.FXMLController;
import com.hnust.service.TestPaperService;
import com.hnust.store.AutoPaperDataStore;
import com.hnust.store.DataStore;
import com.hnust.util.NumberJudge;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import org.springframework.beans.factory.annotation.Autowired;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;

/**
 * 创建人：zhangRuWang
 * 创建时间：2020/10/29
 * 描述：
 */
@FXMLController
public class AutoPaperController implements Initializable {
    @Autowired
    private MainController mainController;
    @Autowired
    private NumberJudge numberJudge;
    @Autowired
    private DataStore dataStore;
    @Autowired
    private AutoPaperDataStore autoPaperDataStore;
    @Autowired
    private TestPaperService testPaperService;
    @FXML
    public ScrollPane container;
    @FXML
    public AnchorPane contain;
    @FXML
    public HBox contain_process;
    @FXML
    public HBox line1;
    @FXML
    public HBox line2;
    @FXML
    public HBox line3;
    @FXML
    public TextField examGradeMajorTextField;
    @FXML
    public TextField examTimeLengthTextField;
    @FXML
    public ComboBox<String> courseNameCombox;
    @FXML
    public Label collegeNameLabel;
    @FXML
    public DatePicker outExamTimeDatePicker;
    @FXML
    public Label teacherNameLabel;
    @FXML
    public TextField passRateTextField;
    @FXML
    public RadioButton aExamRadioButton;
    @FXML
    public RadioButton bExamRadioButton;
    private ToggleGroup toggleGroup=new ToggleGroup();
    private ObservableList<String> list= FXCollections.observableArrayList();
    private List<CourseData> allList=new ArrayList<>();
    private String defaultValue="暂未加入课程组";
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        container.parentProperty().addListener((observable, oldValue, newValue) -> {
            if(newValue!=null){
                if(autoPaperDataStore.getFlag()!=1){
                    clearData();
                }
                getData();
            }else{
                autoPaperDataStore.setFlag(0);
            }
        });
        listenChange();
        initApparent();
    }
    //根据窗口改变，进行监听设置页面大小
    public void listenChange(){
        //通过监听最外层容器的宽度，来改变内层Anchor的宽度
        container.widthProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                contain.setPrefWidth((double)newValue-2);
            }
        });
        //通过监听最外层容器的高度，来改变内层Anchor的高度
        container.heightProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                contain.setPrefHeight((double)newValue-2);
            }
        });
        //设置线条的长度
        contain_process.widthProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                line1.setPrefWidth((double)newValue*0.10);
                line2.setPrefWidth((double)newValue*0.10);
                line3.setPrefWidth((double)newValue*0.10);
            }
        });
    }
    //初始化页面
    public void initApparent(){
        aExamRadioButton.setToggleGroup(toggleGroup);
        bExamRadioButton.setToggleGroup(toggleGroup);
        toggleGroup.selectToggle(aExamRadioButton);
        collegeNameLabel.setText(dataStore.getCollege_name());
        teacherNameLabel.setText(dataStore.getTeacher_name());
    }
    // 收集表单中所有数据，并提交到store中
    public Boolean collectData(){
        if(!allIsEmpty()){
            try{
                String gradeMajor=examGradeMajorTextField.getText();
                String grade=gradeMajor.substring(0,4);
                if(!numberJudge.isInteger(grade)){
                    throw new Exception();
                }
                autoPaperDataStore.setExamGradeMajor(grade);
            }catch (Exception e){
                Alert alert = new Alert(Alert.AlertType.ERROR, "请正确填写年级专业，如：2018网络工程、计算机科学与技术");
                alert.showAndWait();
                return false;
            }
//            autoPaperDataStore.setExamGradeMajor(examGradeMajorTextField.getText());
            autoPaperDataStore.setExamTimeLength(examTimeLengthTextField.getText().trim());
            for(CourseData courseData:allList){
                if(courseData.getName().equals(courseNameCombox.getValue())){
                    autoPaperDataStore.setCourseId(courseData.getId());
                    break;
                }
            }
            autoPaperDataStore.setCourseName(courseNameCombox.getValue().trim());
            autoPaperDataStore.setOutExamTime(outExamTimeDatePicker.getValue());
            autoPaperDataStore.setPassRate(passRateTextField.getText().trim());
            autoPaperDataStore.setPaperKind((((RadioButton)toggleGroup.getSelectedToggle()).getText()).substring(0,1));
            return true;
        }else {
            Alert alert = new Alert(Alert.AlertType.ERROR, "所填内容均不为空！");
            alert.showAndWait();
            return false;
        }
    }
    //清空所有表单数据,以及store中数据
    public void clearData(){
        examGradeMajorTextField.setText("");
        examTimeLengthTextField.setText("");
        outExamTimeDatePicker.setValue(null);
        courseNameCombox.setItems(null);
        passRateTextField.setText("");
        toggleGroup.selectToggle(aExamRadioButton);
    }
    //为页面相关表单发送请求获取数据并设置combox
    public void getData(){
        //获取老师所加入课程的信息
        testPaperService.getCourseData(new Callback<Result<List<CourseData>>>() {
            @Override
            public void onResponse(Call<Result<List<CourseData>>> call, Response<Result<List<CourseData>>> response) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        list.clear();
                        allList.clear();
                        if(response.body().getData()!=null){
                            allList=response.body().getData();
                            Iterator<CourseData> iterator=response.body().getData().iterator();
                            while(iterator.hasNext()){
                                list.add(iterator.next().getName());
                            }
                        }else {
                            list.addAll(defaultValue);
                        }
                        setCourseNameCombox();
                    }
                });
            }
            @Override
            public void onFailure(Call<Result<List<CourseData>>>call, Throwable t) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        Alert alert = new Alert(Alert.AlertType.ERROR, "请求失败，请检查网络设置！");
                        alert.showAndWait();
                    }
                });
            }
        }, dataStore.getTeacher_id(), dataStore.getToken());

    }
    public Boolean allIsEmpty(){
        if(!"".equals(examGradeMajorTextField.getText().trim())
                &&!"".equals(passRateTextField.getText().trim())
                &&courseNameCombox.getValue()!=null&&courseNameCombox.getValue()!=defaultValue
                &&outExamTimeDatePicker.getValue()!=null
                &&!"".equals(passRateTextField.getText().trim())
                &&toggleGroup.selectedToggleProperty()!=null){
            return false;
        }
        return true;
    }
    //初始化Combox
    public void setCourseNameCombox(){
        if(!list.isEmpty()){
            courseNameCombox.setItems(list);
        }else {
            courseNameCombox.getItems().add(defaultValue);
        }
        courseNameCombox.getSelectionModel().select(0);
    }
    //保存并且进入下一步
    public void next() throws IOException {
        if(collectData()){
            mainController.skipView("自动生成试卷II");
        }
    }
}
